package com.jml.api.ribbon手动实现负载均衡;


import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class ExtRibbonController {

	@Autowired
	private DiscoveryClient discoveryClient;
	@Autowired
	private RestTemplate restTemplate;

	private int reqCount;

	@RequestMapping("/extRibbon")
	public String ribbonClient(){
		String instanceUri = getInstance();
		instanceUri = instanceUri +"/getMember";
		//可以使用httpclient或者RestTemplate调用
		String result = restTemplate.getForObject(instanceUri, String.class);
		return result;
	}
	private String getInstance() {
		List<ServiceInstance> instances = discoveryClient.getInstances("provider");
		if(instances==null||instances.size()<=0){
			return null;
		}
		int instanceSize = instances.size();
		int serviceIndex = reqCount % instanceSize;
		reqCount++;
		return instances.get(serviceIndex).getUri().toString();
	}
}
